#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <ctype.h>
#include <sys/un.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/types.h>
#include <linux/netlink.h>
#include <errno.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <fcntl.h>

int g_fd = -1;

/*
@func
	串口设备初始化
@para
	serial_path:重新初始化的串口路径
@return
	None
@Note
	None
*/
void SerialInit(const char* serial_path)
{
    printf("Serial [%s] Init\r\n", serial_path);
	//g_fd = open(...)
}
/*
@func
	串口设备热拔插初始化
@para
	None.
@return
	-1 : 错误
	> 0 : Netlink 的文件描述符
@note
	None
*/
static int SerialHotPlugInit(void)
{
    const int buffersize = 1024;
    int ret;

    struct sockaddr_nl snl;
    bzero(&snl, sizeof(struct sockaddr_nl));
    snl.nl_family = AF_NETLINK;
    snl.nl_pid = 0; // 或者 getpid()
    snl.nl_groups = 1;

    int s = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
    if (s == -1)
    {
        perror("socket");
        return -1;
    }
    
	int on = 1;
    setsockopt(s, SOL_SOCKET, SO_RCVBUF, &buffersize, sizeof(buffersize)); // 设置缓冲区大小
	setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&on,sizeof(int)); // 设置可重复绑定
  
    ret = bind(s, (struct sockaddr *)&snl, sizeof(struct sockaddr_nl));
    if (ret < 0)
    {
        perror("bind");
        close(s);
    }

	fcntl(s, F_SETFL, fcntl(s, F_GETFL, 0) | O_NONBLOCK); // 设置为非阻塞IO，可以在串口接收线程处理

    return s;
}

/*
@func
	串口设备热拔插检测
@para
	fd : Netlink 的文件描述符
	serial_name : 串口设备的名称（不包含路径）
@return
	0 : 正常
	1 ：设备拔出
	2 ：设备插入
@note
	None
*/
static int SerialHotPlugDetect(int fd, char *serial_name)
{
	char buf[2048 * 2] = {0};
	char serial_type[32] = {0};

	sscanf(serial_name, "%[A-Z,a-z]", serial_type); //取设备名，不包含最后的数字, 因为我的设备号会变，可能会 由 ttyUSB0 变成 ttyUSB1

	if (recv(fd, &buf, sizeof(buf), 0) > 0)
	{
        printf("%s\r\n", buf);
		if (NULL != strstr(buf, serial_type) && NULL != strstr(buf, "remove")) // 拔出时内核会发送消息为:remove@/.../ttyUSBx
			return 1;
		if (NULL != strstr(buf, serial_type) && NULL != strstr(buf, "add")) // 插入时内核会发送消息为:add@/.../ttyUSBx
		{
			char *pos = strrchr((const char *)buf, '/') + 1;
			memcpy(serial_name, pos, strlen(buf) - (pos - buf));
			return 2;
		}
	}
	return 0;
}

// 串口工作线程
static void *p_SerialThread(void *arg)
{
	pthread_detach(pthread_self());

	char serial_name[32] = {0};
	char serial_path[32] = {0};
	char *pos = NULL;

	int iHotPlugFd = SerialHotPlugInit(); // 初始化 netlink   
	if(iHotPlugFd < 0)
	{
		printf("create hot plug fd failed[%d]\r\n",iHotPlugFd);
	}
	if(NULL != arg)
	{
		memcpy(serial_path, (char *)arg, strlen((char *)arg));
    	pos = strrchr((const char *)serial_path, '/') + 1;
		memcpy(serial_name, pos, strlen(serial_path) - (pos - serial_path));
		printf("[Serial Thread]:serial path %s, name %s\r\n", serial_path, serial_name);
	}

	uint8_t com_recv_buff[1024];
	uint32_t com_recv_len = 0;

	while (1)
	{
		//判断热插拔信息
		int iHotPlugRes = SerialHotPlugDetect(iHotPlugFd, (char *)serial_name);
		switch(iHotPlugRes)
		{
			case 1:
			{
				printf("Remove Serial\r\n");
			}
			break;
			case 2:
			{
				printf("Add Serial, name %s\r\n", serial_name);
				close(g_fd);
				memcpy(pos, serial_name, strlen(serial_name));
				SerialInit((const char *)serial_path);
			}
			break;
			default: break;
		}
		// 处理串口读取
		com_recv_len = read(g_fd, &com_recv_buff, 1024);
		
		
		usleep(10 * 1000);
	}
}

int main()
{
	pthread_t pid;
	char *serial = "dev/ttyUSB0"; // 设备路径

    SerialInit((const char *)serial);

	pthread_create(&pid, NULL, p_SerialThread, (void *)serial);
	pthread_join(pid, NULL);
	return 0;
}

